const express = require("express")
const router = express.Router()
const { v4: uuidv4 } = require('uuid')
const order = require('../modules').order
const info = require('../modules').userInfo
const fs = require('fs')
const path = require('path')
const WxPay = require('wechatpay-node-v3')
const dayjs = require('dayjs')


const BASE_URL = 'https://api.mch.weixin.qq.com'
const PAY_URL_V3 = BASE_URL + '/v3/pay/transactions/jsapi'
const randomStr = '75B155E2CBD05576B440EEE5C5D51B0B'
const serial_no = '21A736E4E347122570EFAF541877A0B65A2739E2'
const APP_ID = 'wx2ae8ccf82dc3ac05'
const MCH_ID = '1670283099'

const pay = new WxPay({
    appid: APP_ID,
    mchid: MCH_ID,
    publicKey:  fs.readFileSync(path.resolve(__dirname, '../sslcert/apiclient_cert.pem')), // 公钥
    privateKey: fs.readFileSync(path.resolve(__dirname, '../sslcert/apiclient_key.pem')), // 秘钥
  });

router.post('/payV3',async (req,res)=>{
    const body = req.body
    const out_trade_no = uuidv4().replace(/-/g,'')
    const data = {
        appid:APP_ID,
        mchid: MCH_ID,
        out_trade_no: out_trade_no,
        notify_url: 'https://www.roseannepark.love/api/payNotify',
        ...body
    }
    // const signature = pay.getSignature('POST', randomStr, time, '/v3/pay/transactions/jsapi', data);
    // const authorization = pay.getAuthorization(randomStr, time, signature);
    // const headers = {
    //     'Authorization': authorization,
    //     'Accept': 'application/json',
    //     'Content-Type': 'application/json'
    // }
    let response = {
        data: {}
    }
    try{
        // response = await axios.default.post(PAY_URL_V3,data,{
        //     headers: headers,
        // })
        response = await pay.transactions_jsapi(data)
        // console.log('response', response.data)
        response.data.out_trade_no = out_trade_no
        // response.data.timeStamp = time
        // response.data.nonceStr = out_trade_no
        // const str = [APP_ID, time, out_trade_no, data.package, ''].join('\n');
        // response.data.paySign = signature
        await order.create({
            openid: body.payer.openid,
            out_trade_no: out_trade_no,
            transaction_id: "",
            description: body.description,
            price: body.amount.total,
            statu: 0,
            pay_info: ""
        })
    }catch(err){
        console.log('err',err)
    }
    res.send({msg:"ok", data: response.data})
})

router.post("/veriyOrder", async (req,res)=>{
    const body = req.body
    const out_trade_no = body.out_trade_no
    const result = await order.findOne({"out_trade_no": out_trade_no})
    let _order = result
    let statu = result.statu
    const people = await info.findOne({'openid': _order.openid})
    let _isVipExpire = people.isVipExpire
    if (result.statu != 1){
        _order = await pay.query(body)
        statu = _order.data.trade_state == 'SUCCESS' ? 1 : 2
        if(statu == 1){
            const isExpire = people.isVipExpire == 0 ? true : dayjs(people.isVipExpire).diff(dayjs()) > 0 ? false : true
            const expireDate = isExpire ? new Date() : people.isVipExpire
            const days = _order.data.amount.total == 500 ? 30 : _order.data.amount.total == 1300 ? 90 : 365
            const isVipExpire = dayjs(expireDate).add(days, 'day').format('YYYY-MM-DD HH:mm:ss')
            _isVipExpire = isVipExpire
            await people.updateOne({isVip: 1, isVipExpire: isVipExpire})
        }
    }
    // console.log('veriyOrder', _order)
    res.send({"msg":"ok", result: { statu: statu, expireDate: _isVipExpire }})
})


router.all('/payNotify',async (req,res)=>{
    console.log('payNotify', req.body)
    const result = await pay.decipher_gcm(req.body.resource.ciphertext,req.body.resource.associated_data,req.body.resource.nonce,"hebinwenloveroseannepark11180211")
    console.log('payNotify result', result)
    statu = 2
    if (result.trade_state == 'SUCCESS' ){
        statu = 1
    }
    const _openid = result.payer.openid
    await order.findOneAndUpdate({ 'out_trade_no': result['out_trade_no'] }, {"$set": {statu: statu, pay_info: result, transaction_id: result['transaction_id']}})
    if (statu == 1){
        const _people = await info.findOne({'openid': _openid})
        const isExpire = _people.isVipExpire == 0 ? true : dayjs(_people.isVipExpire).diff(dayjs()) > 0 ? false : true
        const expireDate = isExpire ? new Date() : _people.isVipExpire
        const days = result.amount.total == 500 ? 30 : result.amount.total == 1300 ? 90 : 365
        const isVipExpire = dayjs(expireDate).add(days, 'day').format('YYYY-MM-DD HH:mm:ss')
        await _people.updateOne({isVip: 1, isVipExpire: isVipExpire})
    }
    res.send({msg:"ok","code":"SUCCESS"})
})

router.post('/queryOrder', async(req,res)=>{
    const body = req.body
    const result = await pay.query({out_trade_no: body.out_trade_no})
    res.send({msg:"ok", result: result.data})
})

router.get('/getVipInfo', async(req, res)=>{
    const result = await order.where({statu: 1});
    let data = { "月卡": 0, "季卡": 0, "年卡": 0 }
    result.forEach(item=>{
        if(item.description == '月卡'){
            data['月卡'] += 1
        }else if(item.description == '季卡'){
            data['季卡'] += 1
        }else{
            data['年卡'] += 1
        }
    })
    res.send({msg:"ok", data: data})
})

module.exports = router;
